/*
 * @Author: cl
 * @Description:
 * @Date: 2023-04-18 11:13:18
 * @LastEditTime: 2023-05-08 17:07:59
 * @FilePath: \jsnode\nestjs\naota\src\score\score.service.ts
 * @LastEditors: cl
 */
import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Student } from 'src/student/entities/student.entity'
import { Repository } from 'typeorm'
import { CreateScoreDto } from './dto/create-score.dto'
import { UpdateScoreDto } from './dto/update-score.dto'
import { Score } from './entities/score.entity'

@Injectable()
export class ScoreService {
  constructor(
    @InjectRepository(Score) private readonly score: Repository<Score>,
    @InjectRepository(Student) private readonly student: Repository<Student>,
  ) {}

  async create(createScoreDto: CreateScoreDto) {
    let student = await this.student.findOne({ where: { id: createScoreDto.student_id } })
    const score = new Score()
    score.student_id = createScoreDto.student_id
    score.subject_id = createScoreDto.subject_id
    score.achievement = createScoreDto.achievement
    score.student = student
    return await this.score.save(score)
  }

  async findAll(stuId:number) {
    // const list = await this.score.find({
    //   where:{
    //     student_id:stuId
    //   },
    //   relations:['student']
    // })
    const list = this.score
      .createQueryBuilder('score')
      .leftJoinAndMapOne("score.stuName", Student, "student", "student.id=score.studentId")
      .getMany();
    return list
  }

  findOne(id: number) {
    return `This action returns a #${id} score`
  }

  update(id: number, updateScoreDto: UpdateScoreDto) {
    return `This action updates a #${id} score`
  }

  async remove(id: number) {
    const list  = await this.score.delete(id)
    return `This action removes a #${id} score`
  }
}
